package com.suqiu.utils;

import com.alibaba.fastjson.JSONObject;
import com.suqiu.common.utils.EmailConfigModuleParam;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Demo1 {

    private Map<String, String> single;


    private Map<String, List<Map<String, String>>> table;

    private Map<String, List<String>> map;

    public static void main(String[] args) {
//        String s = "{\"list_a\":[\"param\",\"code\"], \"list_A\":[\"orderNo\",\"money\"],\"list_B\":[\"orderNo\",\"money\"],\"list_D\":[\"orderNo\",\"money\"]}";
//
//        LinkedHashMap linkedHashMap = JSONObject.parseObject(s, LinkedHashMap.class);
//        System.out.println(linkedHashMap);

        AtomicReference<String> html = new AtomicReference<>("<!DOCTYPE html>\n" +
                "<html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\">\n" +
                "<head>\n" +
                "  <meta charset=\"utf-8\" />\n" +
                "  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n" +
                "  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\" />\n" +
                "  <title>Welcome to the INDI Newsletter!</title>\n" +
                "  <style>\n" +
                "    /* @media screen and (min-width: 375px) {\n" +
                "html {\n" +
                "  font-size: calc(100% + 2 * (100vw - 375px) / 39);\n" +
                "  font-size: calc(16px + 2 * (100vw - 375px) / 39);\n" +
                "}\n" +
                "}\n" +
                "@media screen and (min-width: 414px) {\n" +
                "html {\n" +
                "  font-size: calc(112.5% + 4 * (100vw - 414px) / 586);\n" +
                "  font-size: calc(18px + 4 * (100vw - 414px) / 586);\n" +
                "}\n" +
                "}\n" +
                "@media screen and (min-width: 600px) {\n" +
                "html {\n" +
                "  font-size: calc(125% + 4 * (100vw - 600px) / 400);\n" +
                "  font-size: calc(20px + 4 * (100vw - 600px) / 400);\n" +
                "}\n" +
                "}\n" +
                "@media screen and (min-width: 1000px) {\n" +
                "html {\n" +
                "  font-size: calc(137.5% + 6 * (100vw - 1000px) / 1000);\n" +
                "  font-size: calc(22px + 6 * (100vw - 1000px) / 1000);\n" +
                "}\n" +
                "} */\n" +
                "    html {\n" +
                "      font-size: max(15px,1.04vw);\n" +
                "      line-height: max(20px,1.45vw);\n" +
                "    }\n" +
                "    h1,h2,h3 {\n" +
                "      margin: 0;\n" +
                "      font-weight: 500;\n" +
                "    }\n" +
                "    body,\n" +
                "    a {\n" +
                "      color: #fff;\n" +
                "      text-align: center;\n" +
                "      margin: 0;\n" +
                "    }\n" +
                "    a {\n" +
                "      text-decoration: underline;\n" +
                "    }\n" +
                "    table {\n" +
                "      width: 100%;\n" +
                "      border-collapse: collapse;\n" +
                "    }\n" +
                "    th {\n" +
                "      background-color: rgba(255, 255, 255, 0.84);\n" +
                "      color: #cf8152;\n" +
                "    }\n" +
                "    th,td {\n" +
                "      border: 2px solid #fff;\n" +
                "      font-weight: 500;\n" +
                "    }\n" +
                "    td {\n" +
                "      padding: max(10px,1.56vw) 0;\n" +
                "    }\n" +
                "    .mb-48 {\n" +
                "      margin-bottom: 48px;\n" +
                "    }\n" +
                "    .mb-22 {\n" +
                "      margin-bottom: 22px;\n" +
                "    }\n" +
                "    .mb-50 {\n" +
                "      margin-bottom: 50px;\n" +
                "    }\n" +
                "    .fz-14 {\n" +
                "      font-size: max(12px,0.73vw);\n" +
                "    }\n" +
                "    .fz-18 {\n" +
                "      font-size: max(15px,0.93vw);\n" +
                "    }\n" +
                "    .fz-24 {\n" +
                "      font-size: max(18px,1.25vw);\n" +
                "    }\n" +
                "    .fz-28 {\n" +
                "      font-size: max(22px, 1.6vw);\n" +
                "    }\n" +
                "    .flex-content {\n" +
                "      display: flex;\n" +
                "      flex-wrap: wrap;\n" +
                "      justify-content: center;\n" +
                "    }\n" +
                "  </style>\n" +
                "</head>\n" +
                "\n" +
                "<body>\n" +
                "<img src=\"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201808%2F21%2F20180821222413_ofqfj.jpg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653447217&t=48c951bf4d20d42cf296f381a78a32ed\">\n" +
                "<div style=\"background-color: #cf8152;\">\n" +
                "  <div style=\"max-width: 1200px; padding: 2.5em 1em; margin: 0 auto;\">\n" +
                "    <h1 class=\"fz-28 mb-48\" style=\"text-align: center; text-decoration: underline;color: #fff;\">\n" +
                "      Welcome to the INDI Family!\n" +
                "    </h1>\n" +
                "    <div class=\"mb-48\">\n" +
                "      <div  style=\"color: #fff;\">\n" +
                "        Congratulations on reserving your Standard INDI One, and becoming a part of the INDI Family.\n" +
                "      </div>\n" +
                "      <div>\n" +
                "        Here is your confirmation number <span>${orderId}</span>\n" +
                "      </div>\n" +
                "    </div>\n" +
                "    <div>\n" +
                "      <h2 class=\"fz-24 mb-22\">Order Summary</h2>\n" +
                "      <div>\n" +
                "        Here is your confirmation number <span>${orderId}</span>\n" +
                "      </div>\n" +
                "      <table class=\"mb-50\">\n" +
                "        <tr isList=\"true\" listName=\"list_2\">\n" +
                "          <th style=\"width: 25%\">INDI One</th>\n" +
                "          <th style=\"width: 25%\">Price</th>\n" +
                "          <th style=\"width: 25%\">Deposit paid</th>\n" +
                "          <th style=\"width: 25%\">image</th>\n" +
                "        </tr>\n" +
                "        <tr isList=\"true\" listName=\"list_1\">\n" +
                "          <td style=\"width: 25%\">\n" +
                "            <div class=\"flex-content\">\n" +
                "              <span>${secondTitle}</span>\n" +
                "              <span>${orderId}</span>\n" +
                "            </div>\n" +
                "          </td>\n" +
                "          <td style=\"width: 25%\"><span>${price}</span></td>\n" +
                "          <td style=\"width: 25%\"><span>${deposit}</span></td>\n" +
                "          <td style=\"width: 25%\"><img src=\"${image}\"> </td>\n" +
                "        </tr>\n" +
                "      </table>\n" +
                "    </div>\n" +
                "    <div class=\"fz-18 mb-50\">\n" +
                "      You will receive a follow up email regarding next steps in the coming weeks.\n" +
                "    </div>\n" +
                "    <div>\n" +
                "      <h3 class=\"fz-24 mb-50\" style=\"text-align: center;color: #fff;\">#You Do You. We Do Cars.</h3>\n" +
                "    </div>\n" +
                "    <div class=\"mb-22\">\n" +
                "      INDI One <a>Order Agreement</a>, <a>Term of Use</a>, and <a>Privacy Notice</a>\n" +
                "    </div>\n" +
                "    <div class=\"fz-14\">\n" +
                "      <div>*Exclusive reservation gift design subject to change. Pictures show pre-production level vehicle.</div>\n" +
                "      <div>**The INDI One is currently only available in the U.S. and Canada. Exclusive reservation gift is non-exchangeable.</div>\n" +
                "    </div>\n" +
                "    <div id=\"div1\">\n" +
                "\n" +
                "    </div>\n" +
                "  </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "<script>\n" +
                "  var div1=document.getElementById(\"div1\");\n" +
                "  div1.innerText=\"suqiu test\";\n" +
                "</script>\n" +
                "</html>\n");

        String regex = "\\$\\{.*\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(html.get());
        Document document = Jsoup.parse(html.get());
        EmailConfigModuleParam emailConfigModuleParam = new EmailConfigModuleParam();
        List<Object> single = new ArrayList<>();
        Map<String, List<Object>> table = new HashMap<>();
        // 找出标识的列表 eg. <tr>
        Elements elementsByAttributeValue = document.getElementsByAttributeValue("isList", "true");
        for (Element element : elementsByAttributeValue) {
            String listName = element.attr("listName");
            table.put(listName, new ArrayList<Object>());
        }

        // 找出占位参数
        while (matcher.find()) {
            // 占位参数:${param}
            String value = matcher.group();
            // 占位参数截取：${param} -> "param"
            String paramValue = value.substring(2, value.length() - 1);
            // 标识的列表添加属性
            elementsByAttributeValue.stream().map(n -> {
                        // 如果子标签有带占位并且该标签没添加过列表属性
                        if (n.getElementsContainingOwnText(value).size() > 0 && StringUtils.isEmpty(n.attr("th:each"))) {
                            n.attr("th:each", "var:${table.tableParam." + n.attr("listName") + "}");
                        }
                        return n;
                    }

            ).collect(Collectors.toList());
            Elements elements = document.getElementsContainingOwnText(value);
            Elements src = document.getElementsByAttributeValue("src", value);
            // 图片标签
            for (Element element : src) {
                Element var = element;
                // 循环查询父节点，直到找到带有列表属性的标签
                while (var != null && !var.attr("isList").equals("true")) {
                    var = var.parent();

                }
                if (var == null) {
                    // 找不到，则为普通占位参数
                    element.attr("th:src", value);
                    single.add(paramValue);
                } else {
                    // 列表参数添加属性
                    element.attr("th:src", "${var.tableKeyValueParam." + paramValue + "}");
                    String listName = var.attr("listName");
                    List<Object> tableParam = table.get(listName);
                    tableParam.add(paramValue);
                    table.put(listName, tableParam.stream().distinct().collect(Collectors.toList()));
                }
            }
            for (Element valueElement : elements) {
                Element var = valueElement;
                // 循环查询父节点，直到找到带有列表属性的标签
                while (var != null && !var.attr("isList").equals("true")) {
                    var = var.parent();

                }
                if (var == null) {
                    // 找不到，则为普通占位参数
                    valueElement.attr("th:text", "${single." + paramValue + "}");
                    single.add(paramValue);
                } else {
                    // 列表参数
                    valueElement.attr("th:text", "${var.tableKeyValueParam." + paramValue + "}");
                    String listName = var.attr("listName");
                    List<Object> tableParam = table.get(listName);
                    tableParam.add(paramValue);
                    table.put(listName, tableParam);
                }

            }
        }
        emailConfigModuleParam.setSingle(single.stream().distinct().collect(Collectors.toList()));
        emailConfigModuleParam.setTable(table);
        System.out.println(JSONObject.toJSON(emailConfigModuleParam));
        System.out.println(document.html());
    }

}
